#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

char toExec[] = "/bin/python3";
char *argv[] = {toExec, "./subprocesstest.py", NULL};
char *envp[]={"PATH=/bin", NULL};

int main(){
	printf("@ test for subprocess \n");
	pid_t pid;
	int child_output[2];
	int child_input[2];
	
	int status;
	
	// create pipe for two process
	if (pipe(child_output) < 0) {
		perror("pipe err \n");
		exit(1);
	}
	if (pipe(child_input) < 0) {
		perror("pipe err \n");
		exit(1);
 	}
 
 	// create child
	pid = fork();
	if (pid < 0){
		perror("fork failed");
		exit(1);
	}
	
	// child
	if (pid == 0){
		//将子进程的输出由标准输出重定向到 cgi_ouput 的管道写端上
		dup2(child_output[1], 1);
		//将子进程的输出由标准输入重定向到 cgi_ouput 的管道读端上
		dup2(child_input[0], 0);
		//关闭 ouput 管道的读端与input 管道的写端
		close(child_output[0]);
		close(child_input[1]);
  
        if(execve(toExec, argv, envp) < 0)
        {
            printf("subprocess execve error");
            exit(1);
        }
	}
	// father
	else{
		//父进程则关闭了output管道的写端和 input 管道的读端
		close(child_output[1]);
		close(child_input[0]);
		
		//然后从 child_output 管道中读子进程的输出
		char c;
		printf("recv from child: \n");
		while (read(child_output[0], &c, 1) > 0){
			printf("%c", c);
		}
		//关闭管道
		close(child_output[0]);
		close(child_input[1]);
		//等待子进程的退出
		waitpid(pid, &status, 0);
	}

	return 0;
}
